<template>
  <view class="content">
    <umeCalender ref="calendarCmp" @dateClick="dateClick" @monthChange="monthChange" />
    <view class="node-box">
      <view class="row-node">
        <view class="node-flag" />
        <view class="node-name">本月累计</view>
        <view class="stat-icon" @click="toStatisticsPage">
          <TnIcon name="statistics" />查看统计
        </view>
      </view>
      <view v-if="monthBill.total > 0" class="month-total">
      ￥<TnCountTo
          start="0"
          :end="monthBill.total"
          :decimals="2" 
          :duration="1000"
          thousands-separator=","
        />
      </view>
      <view v-else class="no-bill">
        💖 恭喜，本月无账单！
      </view>
      <view class="row-node">
        <view class="node-flag" />
        <view class="node-name">
          今日账单
        </view>
        <view v-if="dateBill.total > 0" class="r-text">
          小计<text class="num-total">{{ dateBill.total }}</text>元
        </view>
      </view>
    </view>
    
    <view v-if="dateBill.total > 0" class="bill-list">
      <template v-for="item in dateBill.data">
        <view class="item" @click="toEditBill(item)">
          <view class="bill-desc">
            <view class="name">
              {{ item.bill_name }}
            </view>
            <view class="note">
              {{ item.note}}
            </view>
          </view>
          <view class="amount">
            ￥{{ item.moneyStr }}
          </view>
        </view>
      </template>
    </view>
    <view v-else class="no-bill">
      👍️ 今日无账单，点赞！
    </view>
    
   <!-- <scroll-view direction="vertical">
      <view style="background-color:beige;">11</view>
      <view style="background-color:#667788;">22</view>
      <view style="background-color: #a461e3;">33</view>
    </scroll-view> -->
    
    <!-- 绝对定位的按钮 -->
    <view class="fix-btn" @click="toPageStatement">＋</view>
  </view>
</template>

<script setup>
  import { ref, onMounted, reactive } from 'vue';
  import { onShow, onLoad } from '@dcloudio/uni-app';
  import { callCloudFunction } from '@/utils/cloudfunc';
  import umeCalender from '@/components/umeCalendar.vue'
  import TnCountTo from '@/uni_modules/tuniaoui-vue3/components/count-to/src/count-to.vue'
  import TnIcon from '@/uni_modules/tuniaoui-vue3/components/icon/src/icon.vue'
  import { dateFormat } from '@/utils';
  const calendarCmp = ref(null)
  
  const dateBill = reactive({
    data: [],
    total: 0
  })
  
  const monthBill = reactive({
    data: [],
    total: 0
  })
  
  onShow(() => {
    // 查询当前账单
    const cdt = new Date()
    let curTimestamp = new Date(cdt.getFullYear(), cdt.getMonth(), cdt.getDate()).getTime()
    if (calendarCmp.value) {
      const fd = calendarCmp.value.getFlagDate()
      curTimestamp = new Date(fd.year, fd.month, fd.date).getTime()
    }
    getDateBillList(curTimestamp) // 日账单
    getMonthBillList(curTimestamp) // 月账单
  })
  
  const toStatisticsPage = () => {
    let pageUrl = '/pages/account/statistics/index'
    if (calendarCmp.value) {
      const fd = calendarCmp.value.getFlagDate()
      console.log(fd);
      pageUrl += `?y=${fd.year}&m=${fd.month}`
    }
    uni.navigateTo({
      url: pageUrl
    })
  }

  const dateClick = (item) => {
    // console.log(item);
    const ts = new Date(item.year, item.month, item.date).getTime()
    getDateBillList(ts)
  }
  const monthChange = (monthObj) => {
    // console.log(monthObj);
    getMonthBillList(new Date(monthObj.year, monthObj.month, 1).getTime())
    if (calendarCmp.value) {
      const fd = calendarCmp.value.getFlagDate()
      // console.log('fd', fd);
      const ctd = new Date(fd.year, fd.month, fd.date)
      if (dateFormat(new Date(), '', true) == dateFormat(ctd, '', true)) {
        getDateBillList(ctd.getTime())
        return
      }
    } 
    dateBill.data = []
    dateBill.total = 0
  }
  
  const toEditBill = (bill) => {
    // console.log(bill)
    uni.navigateTo({
      url: '/pages/account/statement/index?_id=' + bill._id,
    })
  }
  
  // 查询日期账单
  const getDateBillList = (dateTimeStamp) => {
    uni.showLoading({
      title: '加载日账单'
    })
    callCloudFunction({
      name: 'ledger-bill',
      data: {action: 'getDateBill', date_timestamp: dateTimeStamp},
    })
    .then(res => {
      uni.hideLoading()
      let dateTotal = 0
      dateBill.data = res.bills.map(item => {
        dateTotal += item.money;
        item.moneyStr = Number(item.money / 100).toFixed(2)
        return item
      })
      dateBill.total = Number(dateTotal / 100).toFixed(2)
    })
  }
  
  // 查询月账单
  const getMonthBillList = (dateTimeStamp) => {
    uni.showLoading({
      title: '加载月账单'
    })
    callCloudFunction({
      name: 'ledger-bill',
      data: {action: 'getMonthBill', date_timestamp: dateTimeStamp},
    })
    .then(res => {
      // console.log('月账单返回:', res)
      uni.hideLoading()
      let monthTotal = 0
      monthBill.data = res.bills.map(item => {
        monthTotal += item.money;
        item.moneyStr = Number(item.money / 100).toFixed(2)
        return item
      })
      monthBill.total = Number(monthTotal / 100).toFixed(2)
      setCalendarBill()
    })
  }
  
  // 设置日历显示账单
  const setCalendarBill = () => {
    // 计算每日的小计
    let dateTotallBill = {}
    for (let i=0; i < monthBill.data.length; i++) {
      let item = monthBill.data[i]
      let dt = new Date(item.bill_time)
      let key = `${dt.getFullYear()}${dt.getMonth()}${dt.getDate()}`
      dateTotallBill[key] = (dateTotallBill[key] || 0 ) + item.money
    }
    for (let dkey in dateTotallBill) {
      let n = dateTotallBill[dkey]
      let style = n > 10000 ? 'color: #cb4b16;font-size:22rpx' : 'font-size:22rpx'
      dateTotallBill[dkey] = ['￥' + Number(n /100).toFixed(2), style]
    }
    // console.log(dateTotallBill)
    if (calendarCmp.value) {
      calendarCmp.value.setUmeDateText(dateTotallBill)
    }
  }
  
  // 跳转账单添加
  const toPageStatement = () => {

    uni.navigateTo({
      url: '/pages/account/statement/index',
    })
  }
  
</script>

<style lang="scss">
  .content {
    .node-box {
      // padding: 20rpx;
      border-bottom: 1px solid #eee;
      .row-node {
        background-color: #e8e8ff;
        height: 40rpx;
        padding-right: 20rpx;
        // margin-bottom: 20rpx;
        display: flex;
        justify-content: flex-start;
        flex-direction: row;
        align-items: center;
        &:last-child {
          margin-bottom: 0;
        }
        .node-flag {
          width: 10rpx;
          height: 100%;
          // border-radius: 10rpx;
          background-color: #f0ad4e;
        }
        .node-name {
          line-height: 40rpx;
          margin-left: 10rpx;
          font-weight: 700;
        }
        .stat-icon {
          margin-left: auto;
        }
        .r-text {
          margin-left: auto;
          .num-total {
            color: #cb2d01;
            font-weight: 700;
            padding: 0 10rpx;
          }
        }
      }
      .month-total {
        // line-height: 60rpx;
        font-weight: 700;
        font-size: 30rpx;
        color: #cb2d01;
        padding: 20rpx;
        --tn-text-color-primary: #cb2d01;
      }
    }
    
    .bill-list {
      .item {
        display: flex;
        align-items: center;
        height: 70rpx;
        border-bottom: 1px solid #f9f9f9;
        padding: 10rpx 20rpx;
        .name {
          font-size: 30rpx;
          // line-height: 40rpx;
        }
        .note {
          font-size: 22rpx;
          color: #888;
          // line-height: 30rpx;
        }
        .amount {
          margin-left: auto;
          line-height: 70rpx;
        }
      }
    }
    .no-bill {
      padding: 20rpx;
      color: #94d5ff;
    }
    
    .fix-btn {
      position: fixed;
      bottom: 60rpx;
      right: 40rpx;
      border-radius: 40rpx;
      box-shadow: 0 0 12rpx 0rpx #bbb;
      background-color: rgba(255, 255, 255, 0.8);
      font-size: 50rpx;
      width: 80rpx;
      height: 80rpx;
      display: flex;
      justify-content: center;
      align-items:center;
    }
  }
</style>
